package com.example.springbook.Controller;

import com.example.springbook.Model.BookInfo;
import com.example.springbook.Model.PageRequest;
import com.example.springbook.Model.PageResult;
import com.example.springbook.Service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RequestMapping("/book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;


    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo){
        if(!StringUtils.hasLength(bookInfo.getBookName())
           ||!StringUtils.hasLength(bookInfo.getAuthor())
                ||bookInfo.getCount() == null
                ||!StringUtils.hasLength(bookInfo.getPublish())
                ||bookInfo.getStatus() ==null
                ||bookInfo.getPrice()==null
        ){
            return "输入的参数不合法";
        }
        try {
            Integer result=bookService.insertBook(bookInfo);
            if(result > 0){
                return "";
            }
        }catch (Exception e){
            log.error("添加图书异常");
        }
        return "添加图书失败";
    }

    @RequestMapping("/getBookListByPage")
    public PageResult<BookInfo> getBookListByPage(PageRequest pageRequest){
        return bookService.getBookListByPage(pageRequest);
    }

    /**
     * 修改图书
     */
    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId){
         BookInfo bookInfo=bookService.queryBookById(bookId);
         return bookInfo;
    }

    //进行图书的修改
    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo){
        try {
            bookService.updateBook(bookInfo);
            return "";
        } catch (Exception e) {
            log.error("修改图书失败", e);
            return e.getMessage();
        }
    }

    /**
     * 删除图书
     */
    @RequestMapping("deleteBook")
    public String deleteBook(Integer bookId){
        try {
            Integer result=bookService.deleteBook(bookId);
            if(result > 0){
                return "";
            }
            return "内部错误";
        }catch (Exception e){
            return "内部错误";
        }
    }

    @RequestMapping("/batchDeleteBook")
    public String batchDeleteBook(@RequestParam List<Integer> ids){
        Integer result=bookService.batchDeleteBook(ids);
        if (result > 0){
            return "";
        }
        return "批量删除错误";
    }


}
